import React from 'react';
import { connect } from 'dva';
import { Select, Switch, Button, Table, Pagination, Input, message, Modal } from 'antd';
import { VtxGrid } from 'vtx-ui';
import { NAME_SPACE, Add_Form,SearchParams } from '../../../components/PeoInfoManage/config'
import styles from './peoInfoManage.less'
import moment from 'moment'
import _ from 'lodash'
import Action from '../../../components/PeoInfoManage/Action'
import AddItem from '../../../components/PeoInfoManage/AddItem'
import ViewItem from '../../../components/PeoInfoManage/ViewItem'
import request from '../../../utils/request'

const Option = Select.Option

const Index = ({dispatch, peoInfoManage}) => {
  
  const {
    loading,
    pageNo,
    pageSize,
    total,
    searchParams,
    oldSearchParams,
    selectedRowKeys,
    paramsList,
    dataList,
    newDataList,
    peopleList,
    // 详情可见
    detailsModelVisable,
    details,
    // 添加可见
    addModelVisable,
    addForm,
    default_columns,
    // 编辑
    edit,
    // 姓名
    name,
    modifyId,
  } = peoInfoManage;
  
  const vtxGridProps = {
    titles: ['作业人员'],
    gridweight: [1],
    // 点击确定
    confirm: () => {
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'search'
        }
      })
    },
    // 重置
    clear: () => {
      dispatch({
        type:`${NAME_SPACE}/updateState`,
        payload:{
            searchParams: {
                ...SearchParams
            },
            pageNo: 1,
            pageSize: 20,
        }
      });
      dispatch({
          type:`${NAME_SPACE}/getList`,
          payload:{type:"search"}
      });
    },
  }

  const actionProps = {
    showBtns:['add'],
    addAction: () => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          addModelVisable: true,
          modifyId: "",
          // 每次新增前清空上一次的填写数据
          addForm: {...Add_Form},
        }
      })
    },
  }

  // 搜索条件(优化)
  const changeValue = (value) =>{
    dispatch({
      type: `${NAME_SPACE}/updateSubState`,
      payload: {
        sub: 'searchParams',
        data: {
          userName: value
        }
      }
    })
  }

   // 查看详情
   const viewShow = (id) => {
    dispatch({
      type: `${NAME_SPACE}/getDetail`,
      payload: {
        type: 'view',
        id: id,
      }
    })
  };
  // 编辑
  const addShow = (id) => {
    dispatch({
      type: `${NAME_SPACE}/getDetail`,
      payload: {
        type: 'modify',
        id: id,
      }
    })
  } 

  // 更改状态
  const changeStatues = (checked, id, name) => {
    // console.log(checked)
    let newData = _.cloneDeep(dataList);
    newData.forEach((item, index) => {
      if (item.userId === id) {
          newData[index][name] = checked? '1' : '0';
      }
    })
    dispatch({
      type: `${NAME_SPACE}/updateState`,
      payload: {
        dataList: newData
      },
    })
    dispatch({
      type: `${NAME_SPACE}/updateStatus`,
      payload:{
        id,
        status: checked? '1' : '0'
      }
    })
  }

  const tableProps = {
    autoFit: true,
    scroll:{
      y:`${document.documentElement.clientHeight - 92 - 120}px`,
    },
    hideColumn: true,
    indexColumn: true,
    showHeader: true,
    startIndex: (pageNo) * pageSize + 1,
    dataSource: dataList,
    loading: loading,
    pagination: false,
    columns: [
      {
        title: '序号', 
        key: '0',
        dataIndex: '0',
        ellipsis: true,
        render:(text,record,index)=>`${index+1}`
      },{
        title: '作业人员', 
        key: 'userName',
        dataIndex: 'userName',
        ellipsis: true,
      },{
        title: '手机号', 
        key: 'linkPhone',
        dataIndex: 'linkPhone',
        ellipsis: true,
      },{
        title: '小程序账号', 
        key: 'loginName',
        dataIndex: 'loginName',
        ellipsis: true,
      },{
        title: '小程序密码', 
        key: 'passWord',
        dataIndex: 'passWord',
        ellipsis: true,
      },{
        title: '账号状态', 
        key: 'status',
        dataIndex: 'status',
        ellipsis: true,
        // render:(text,record,index)=>{return text == 1? '冻结' : '正常'}
        render:(text,record,index)=>{
          return (
            <Switch checkedChildren="正常" unCheckedChildren="冻结" checked={text == 0 ? false : true} onChange={(checked) => {changeStatues(checked,record.userId,'status')}}/>
          )
        }
      },{
        title: '操作', 
        key: '6',
        dataIndex: '6',
        ellipsis: true,
        render: (text, record, index) => {
          const id = record.userId
          return(
            <div>
              <a onClick={() => {viewShow(id)}}>查看</a> | <a onClick={() => {addShow(id)}}>编辑</a>
            </div>
          )
        }
      }
    ],
    rowKey: (record, index) => {
      return record.id
    },
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys || [],
      onChange: (selectedRowKeys, selectedRows) => {
        let ids = selectedRows.map((item) => {
            return item.id;
        });
        dispatch({
          type: `${NAME_SPACE}/updateState`,
          payload: {
            selectedRowKeys: ids
          }
        })
      },
    },
  }

  const pagProps = {
    current: pageNo,
    defaultCurrent: 1,
    total: total,
    pageSize: pageSize,
    showQuickJumper: true,
    showSizeChanger: true,
    onChange: (page) => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          pageNo: page
        }
      });
      // 获取新的列表（page）
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'page'
        }
      })
    },
    showTotal: (total) => {
        return `合计${total}条数据`
    },
    onShowSizeChange: (current, pageSize) => {
      dispatch({
        type: `${NAME_SPACE}/updateState`,
        payload: {
          pageNo: 1,
          pageSize: pageSize,
        }
      });
      // 获取新的列表（page）
      dispatch({
        type: `${NAME_SPACE}/getList`,
        payload: {
          type: 'page'
        }
      })
    },
  }

  const addProps = {
    dispatch,
    addModelVisable,
    addForm,
    modifyId,
  }

  const viewProps = {
    dispatch,
    detailsModelVisable,
    details,
  }

  return(
    <div className={styles.normal}>
      <AddItem {...addProps}/>
      <ViewItem {...viewProps}/>
      <div className={styles.searchWarp}>
        <VtxGrid {...vtxGridProps}>
          <Select
            style={{width: '100%'}}
            value={searchParams.userName}
            onChange={(value) => {changeValue(value)}}
            allowClear
            showSearch
            optionFilterProp='children'
          >
            {
              Array.isArray(peopleList)? 
                peopleList.map((item, index) => {
                  return(<Option value={item.userName} key={index}>{item.userName}</Option>)
                })
              :
                ''
            }
          </Select>
        </VtxGrid>  
      </div>
      <Action {...actionProps}/>
      <div className={styles.table} style={{ height: document.documentElement.clientHeight-92 }}>
        <div className={styles.tableContent}>
          <Table {...tableProps}/> 
        </div>  
        <div className={styles.pagination}>
          <span className={styles.pagContent}> <Pagination {...pagProps}/> </span>  
        </div>  
      </div>  
    </div>
  )
}
export default connect(state=>state)(Index)